using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.Doctor;
using B.S.NewMedical.Api.Read.DTOS.Doctor;
using B.S.NewMedical.Domain.Appointment;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Doctor
{
    /// <summary>
    /// 根据ID获取医生信息处理器
    /// </summary>
    public class GetDoctorByIdHandler : IRequestHandler<GetDoctorByIdCommand, ApiResult<DoctorDto>>
    {
        private readonly IBaseRepository<Domain.Appointment.Doctor> _doctorRepository;
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;
        private readonly IBaseRepository<JobTitleModel> _jobTitleRepository;
        private readonly IBaseRepository<HospitalModel> _hospitalRepository;
        private readonly IBaseRepository<HospitalDepartmentModel> _hospitalDepartmentRepository;
        private readonly ILogger<GetDoctorByIdHandler> _logger;
        private readonly IMapper _mapper;

        public GetDoctorByIdHandler(
            IBaseRepository<Domain.Appointment.Doctor> doctorRepository,
            IBaseRepository<DepartmentModel> departmentRepository,
            IBaseRepository<JobTitleModel> jobTitleRepository,
            IBaseRepository<HospitalModel> hospitalRepository,
            IBaseRepository<HospitalDepartmentModel> hospitalDepartmentRepository,
            ILogger<GetDoctorByIdHandler> logger,
            IMapper mapper)
        {
            _doctorRepository = doctorRepository;
            _departmentRepository = departmentRepository;
            _jobTitleRepository = jobTitleRepository;
            _hospitalRepository = hospitalRepository;
            _hospitalDepartmentRepository = hospitalDepartmentRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<DoctorDto>> Handle(GetDoctorByIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取医生信息，ID：{Id}", request.Id);

                // 查询医生信息
                var doctor = await _doctorRepository.GetValue(request.Id);
                if (doctor == null)
                {
                    return new ApiResult<DoctorDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到该医生信息"
                    };
                }

                // 查询科室信息
                var department = await _departmentRepository.GetValue(doctor.Dept_id);

                // 查询职称信息
                var jobTitle = await _jobTitleRepository.GetValue(doctor.JobTitle_id);

                // 查询医院科室关系
                var hospitalDepartment = await _hospitalDepartmentRepository.GetAll()
                    .Where(hd => hd.DepartmentId == doctor.Dept_id)
                    .FirstOrDefaultAsync(cancellationToken);

                // 查询医院信息
                HospitalModel matchedHospital = null;
                if (hospitalDepartment != null)
                {
                    matchedHospital = await _hospitalRepository.GetValue(hospitalDepartment.HospitalId);
                }

                // 创建DTO
                var doctorDto = _mapper.Map<DoctorDto>(doctor);
                
                // 设置科室名称
                doctorDto.DepartmentName = department?.DepartmentName ?? "未知科室";
                
                // 设置职称名称
                doctorDto.JobTitleName = jobTitle?.JobTitle ?? "未知职称";
                
                // 设置医院信息
                if (matchedHospital != null)
                {
                    doctorDto.HospitalId = matchedHospital.Id;
                    doctorDto.HospitalName = matchedHospital.HospitalName ?? "未知医院名称";
                }
                else
                {
                    doctorDto.HospitalId = 0;
                    doctorDto.HospitalName = "未知医院";
                }

                return new ApiResult<DoctorDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取医生信息成功",
                    Data = doctorDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取医生信息时发生异常");
                return new ApiResult<DoctorDto>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取医生信息失败：" + ex.Message
                };
            }
        }
    }
} 